package com.weijian.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weijian.entity.UploadTask;
import com.weijian.mapper.UploadTaskMapper;
import com.weijian.service.UploadTaskService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 上传任务Service实现类
 */
@Service
public class UploadTaskServiceImpl extends ServiceImpl<UploadTaskMapper, UploadTask> implements UploadTaskService {

    @Override
    public UploadTask initUploadTask(String taskId, String fileName, Long fileSize, String fileMd5, Long chunkSize, Integer totalChunks) {
        UploadTask task = new UploadTask();
        task.setTaskId(taskId);
        task.setFileName(fileName);
        task.setFileSize(fileSize);
        task.setFileMd5(fileMd5);
        task.setChunkSize(chunkSize);
        task.setTotalChunks(totalChunks);
        task.setUploadedChunks(0);
        task.setStatus(0); // 初始化状态
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        
        save(task);
        return task;
    }

    @Override
    public UploadTask getUploadTask(String taskId) {
        return lambdaQuery().eq(UploadTask::getTaskId, taskId).one();
    }

    @Override
    public void updateChunkProgress(String taskId, Integer chunkNumber) {
        lambdaUpdate()
                .setSql("uploaded_chunks = uploaded_chunks + 1")
                .set(UploadTask::getUpdateTime, LocalDateTime.now())
                .set(UploadTask::getStatus, 1) // 设置为上传中状态
                .eq(UploadTask::getTaskId, taskId)
                .update();
    }


    @Override
    public void markTaskComplete(String taskId) {
        lambdaUpdate()
            .set(UploadTask::getStatus, 2) // 完成状态
            .set(UploadTask::getUpdateTime, LocalDateTime.now())
            .eq(UploadTask::getTaskId, taskId)
            .update();
    }

    @Override
    public void markTaskFailed(String taskId) {
        lambdaUpdate()
            .set(UploadTask::getStatus, 3) // 失败状态
            .set(UploadTask::getUpdateTime, LocalDateTime.now())
            .eq(UploadTask::getTaskId, taskId)
            .update();
    }
}